package com.campus.counseling.util;

import com.campus.counseling.model.common.exception.ServiceException;
import com.campus.counseling.security.SecurityUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;

public class SecurityUtils {

    private static final Logger log = LoggerFactory.getLogger(SecurityUtils.class);

    public static SecurityUser getLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            log.warn("未找到认证信息");
            return null;
        }
        if (authentication.getPrincipal() instanceof SecurityUser) {
            return (SecurityUser) authentication.getPrincipal();
        }
        log.warn("认证信息类型不正确: {}", authentication.getPrincipal().getClass());
        return null;
    }

    public static Long getCurrentUserId() {
        return getLoginUser().getId();
    }

    public static Long getUserId() {
        SecurityUser user = getLoginUser();
        if (user == null) {
            throw new ServiceException("用户未登录");
        }
        return user.getId();
    }

    public static String getUserRole() {
        SecurityUser user = getLoginUser();
        List<String> roles = user.getRoles();
        return roles != null && !roles.isEmpty() ? roles.get(0) : null;
    }

    public static SecurityUser getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof SecurityUser) {
            return (SecurityUser) authentication.getPrincipal();
        }
        return null;
    }

    public static List<String> getUserRoles() {
        SecurityUser user = getCurrentUser();
        return user != null ? user.getRoles() : null;
    }

    /**
     * 判断当前用户是否为管理员
     * 作用：用于控制权限，只有管理员才能执行某些操作
     * 例如：
     * 1. 管理员可以查看所有预约记录
     * 2. 管理员可以取消任何人的预约
     * 3. 管理员可以管理咨询师信息
     */
    public static boolean isAdmin() {
        String userRole = getUserRole();
        return "admin".equals(userRole) || "superadmin".equals(userRole);
    }

    public static String getCurrentUserRole() {
        SecurityUser user = getLoginUser();
        List<String> roles = user.getRoles();
        return roles != null && !roles.isEmpty() ? roles.get(0) : null;
    }

    public static boolean isStudent() {
        String userRole = getUserRole();
        return "student".equals(userRole);
    }

    public static boolean isCounselor() {
        String userRole = getUserRole();
        return "counselor".equals(userRole);
    }

}